"""
文本上传相关接口
"""
import time
from pathlib import Path
from fastapi import APIRouter, UploadFile, File, HTTPException
from app.models.response import UploadResponse
from app.services.embedding import embedding_service
from app.storage.json_storage import KnowledgeBaseStorage
from app.core.config import settings

router = APIRouter()


@router.post("/upload", response_model=UploadResponse)
async def upload_text_file(file: UploadFile = File(...)):
    """
    上传文本文件并进行向量化处理
    
    - **file**: 要上传的文本文件（仅支持 .txt 格式）
    """
    start_time = time.time()
    
    # 验证文件格式
    if not file.filename.endswith('.txt'):
        raise HTTPException(status_code=400, detail="仅支持 .txt 格式的文件")
    
    try:
        # 读取文件内容
        content = await file.read()
        text = content.decode('utf-8')
        
        # 保存原始文件到 uploads 目录
        uploads_dir = settings.uploads_dir
        uploads_dir.mkdir(parents=True, exist_ok=True)
        file_path = uploads_dir / file.filename
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(text)
        
        # 文本分块
        chunks = embedding_service.chunk_text(text, settings.CHUNK_SIZE)
        
        # 生成向量
        embeddings = embedding_service.create_embeddings(chunks)
        
        # 保存到知识库
        storage = KnowledgeBaseStorage(
            storage_path=settings.knowledge_base_path,
            embedding_model=settings.EMBEDDING_MODEL
        )
        chunk_count = storage.add_document(
            filename=file.filename,
            file_size=len(content),
            chunks_text=chunks,
            embeddings=embeddings,
            chunk_size=settings.CHUNK_SIZE
        )
        
        processing_time = time.time() - start_time
        
        return UploadResponse(
            status="success",
            filename=file.filename,
            chunk_count=chunk_count,
            total_characters=len(text),
            processing_time=round(processing_time, 2)
        )
        
    except UnicodeDecodeError:
        raise HTTPException(status_code=400, detail="文件编码错误，请确保使用 UTF-8 编码")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理文件时发生错误: {str(e)}")

